import axios from 'axios'

const service = axios.create({
  baseURL: '/api',
  timeout: 10000
})

service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 200) {
      return res
    } else {
      return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  error => {
    // 处理HTTP错误
    if (error.response) {
      // 保留原始error对象，以便调用方可以访问status等属性
      const res = error.response.data
      const errorObj = new Error(res && res.message ? res.message : `请求失败: ${error.response.status}`)
      errorObj.response = error.response
      errorObj.status = error.response.status
      return Promise.reject(errorObj)
    } else if (error.request) {
      return Promise.reject(new Error('网络错误，请检查网络连接'))
    } else {
      return Promise.reject(error)
    }
  }
)

export default service

